<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('数据分类')" prop="dataType">
            <dict-select
              v-model="form.dataType"
              dictionary="data_link_type"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('数据名称')" prop="dataName">
            <el-input v-model="form.dataName" :placeholder="$t('数据名称')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('数据编号')" prop="dataNum">
            <el-input v-model="form.dataNum" :placeholder="$t('数据编号')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" :placeholder="$t('备注')" type="textarea" show-word-limit maxlength="250" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <!-- <el-form-item :label="$t('sql')" prop="dataSql">
            <el-input v-model="form.dataSql" type="textarea" :placeholder="$t('sql')" show-word-limit maxlength="1000" />
          </el-form-item> -->
          <el-form-item :label="$t('Sql脚本')" prop="dataSql">
            <textarea ref="dataSql" v-model="form.dataSql" class="codesql" style="height:500px;width:600px;" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-col :span="24">
        <div class="area-header mt-15" style="display: flex;width: 100%;align-items: center;">
          <span class="area-header-title" style="flex: 1;">
            {{ $t('字段列表') }}
          </span>
          <el-button
            type="primary"
            size="mini"
            @click="getColumnBySql"
          >{{ $t('刷新') }}</el-button>
        </div>
        <el-table
          :data="form.columnList"
          style="width: 100%"
          border
        >
          <el-table-column
            align="center"
            prop="fieldName"
            label="字段名字"
          />
          <el-table-column
            align="center"
            prop="fieldAlias"
            label="字段别名"
          >
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('字段别名') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                :prop="'columnList.' + scope.$index + '.fieldAlias'"
                :rules="columnListRules.fieldAlias"
              >
                <el-input v-model="scope.row.fieldAlias" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('字段类型')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('字段类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                :prop="'columnList.' + scope.$index + '.fieldType'"
                :rules="columnListRules.fieldType"
              >
                <el-select
                  v-model="scope.row.fieldType"
                  clearable
                  :placeholder="$t('请选择')"
                  style="width: 100%"
                  @change="updateFormatValue(scope.row)"
                >
                  <el-option
                    v-for="field in filedTypeOptions"
                    :key="field.dictValue"
                    :label="$t(field.dictLabel)"
                    :value="field.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('格式化')" align="center">
            <template slot-scope="scope">
              <el-form-item :prop="'columnList.' + scope.$index + '.fieldType'">
                <el-input v-if="scope.row.fieldType === 'RQ' || scope.row.type === 'JE'" v-model="scope.row.fieldFormat" />
                <el-select
                  v-if="scope.row.fieldType === 'ZD'"
                  v-model="scope.row.fieldFormat"
                  value=""
                  clearable
                  filterable
                  :placeholder="$t('请选择')"
                  style="width: 100%"
                >
                  <el-option
                    v-for="dict in dictOptions"
                    :key="dict.dictType"
                    :label="$t(dict.dictName)"
                    :value="dict.dictType"
                  >
                    <span style="float: left">{{ dict.dictName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictType }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="system:link" />
    </div>
  </div>
</template>

<script>
    import { saveDataLink, getDataLink } from '@/api/dev/datalink/dataLink'
    import { optionselect as getDictOptionselect } from '@/api/system/dict/type'
    import { getColumnBySql } from '@/api/system/search/searchSqlBase'

    import 'codemirror/theme/ambiance.css'
    import 'codemirror/lib/codemirror.css'
    import 'codemirror/addon/hint/show-hint.css'
    const CodeMirror = require('codemirror/lib/codemirror')
    require('codemirror/addon/edit/matchbrackets')
    require('codemirror/addon/selection/active-line')
    require('codemirror/mode/sql/sql')
    require('codemirror/addon/hint/show-hint')
    require('codemirror/addon/hint/sql-hint')
    export default {
       name: 'CodeMirrorr',
        data() {
            return {
                // 表单参数
                form: {
                  columnList: []
                },
                // 遮罩层
                loading: false,
                // 字典信息
                dictOptions: [],
                 // 字段类型字典
                filedTypeOptions: [],
                // 表单校验
                rules: {
                  dataType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  dataName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  dataNum: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  dataSql: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                },
                 columnListRules: {
                  fieldAlias: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  fieldType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                }
            }
        },
        created() {
           /** 查询字典下拉列表 */
          getDictOptionselect().then(response => {
            this.dictOptions = response.data
          })
          this.getDicts('search_field_type').then(response => {
            this.filedTypeOptions = response.data
          })
        },
        mounted() {
          const mime = 'text/x-mariadb'
          // let theme = 'ambiance'//设置主题，不设置的会使用默认主题
          this.editor = CodeMirror.fromTextArea(this.$refs.dataSql, {
            mode: mime, // 选择对应代码编辑器的语言，我这边选的是数据库，根据个人情况自行设置即可
            indentWithTabs: true,
            smartIndent: true,
            lineNumbers: true,
            matchBrackets: true,
            // theme: theme,
            autofocus: true,
            extraKeys: { 'Ctrl': 'autocomplete' }, // 自定义快捷键
            hintOptions: { // 自定义提示选项
              tables: {
                users: ['name', 'score', 'birthDate'],
                countries: ['name', 'population', 'size']
              }
            }
          })
          this.editor.on('cursorActivity', function() {
            if (this !== null) {
              this.editor.showHint()
            }
          })
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                    getDataLink(data.id).then(response => {
                        this.form = response.data
                        this.editor.setValue(this.form.dataSql !== null ? this.form.dataSql : '')
                        this.loading = false
                    }).catch(() => {
                      this.loading = false
                    })
                } else {
                    this.reset()
                    this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    dataType: undefined,
                    dataName: undefined,
                    dataNum: undefined,
                    remark: undefined,
                    dataSql: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined,
                    delFlag: undefined,
                    columnList: []
                }
                this.editor.setValue('')
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm() {
               console.log(this.form)
                 this.form.dataSql = this.editor.getValue()
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        saveDataLink(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        })
                    } else {
                       this.locationError(document)
                    }
                })
           },
           getColumnBySql() {
              this.form.searchSql = this.editor.getValue()
            if (this.form.searchSql === null || this.form.searchSql === '') {
              this.$message.error('sql脚本不能为空')
            } else {
               console.log(this.form, 111)
              getColumnBySql(this.form).then(response => {
                // 保存之前配置的数据
                var fieldTempMap = {}
                console.log(this.form)
                for (var j = 0; j < this.form.columnList.length; j++) {
                  var filed = this.form.columnList[j]
                  fieldTempMap[filed.fieldName] = filed
                }
                var fieldList = []
                for (var i = 0; i < response.data.length; i++) {
                  var field = {}
                  if (fieldTempMap[response.data[i]] !== null && fieldTempMap[response.data[i]] !== undefined) {
                    field = fieldTempMap[response.data[i]]
                  } else {
                    field.fieldName = response.data[i]
                    field.fieldAlias = response.data[i]
                    field.fieldType = 'WB'
                  }
                  fieldList.push(field)
                    this.$set(this.form, 'columnList', fieldList)
                }
                console.log(fieldList)
              })
            }
           },
            // 设置格式化字段默认值
          updateFormatValue: function(row) {
            if (row.fieldType === 'JE') {
              row.fieldFormat = '###,###.####'
            } else if (row.fieldType === 'RQ') {
              row.fieldFormat = 'yyyy-MM-dd'
            }
          }
        }
    }
</script>
<style scoped>
.codesql {
  font-size: 11pt;
  font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
}
</style>

